//
//  ReversiBoardLineRange.m
//  Reversi
//
//  Created by 成瀬 龍人 on 2/5/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "ReversiBoardLineRange.h"
#import "ReversiBoardLineRangeEnumerator.h"

@implementation ReversiBoardLineRange
@synthesize startPosition,direction,numberOfStone;

- (id)init:(ReversiBoardPosition*)start
	   dir:(ReversiBoardLineDirection*)dir
	   num:(int)num{
	int max_x = start.x + dir.x * (num - 1);
	int max_y = start.y + dir.y * (num - 1);
	if ( max_x < 1 || 8 < max_x ||
		 max_y < 1 || 8 < max_y){
		@throw [[ReversiOutOfRangeException alloc] initWithInt:max_x:max_y];
	}
	startPosition = start;
	direction = dir;
	numberOfStone = num;
	return self;
}

- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state 
								   objects:(id *)stackbuf 
									 count:(NSUInteger)len{
	if (state->state >= numberOfStone){
		return 0;
	}
	int count = 0;;
	while (state->state < numberOfStone && count < len) {
		int x = startPosition.x + state->state * direction.x;
		int y = startPosition.y + state->state * direction.y;
		stackbuf[count] = [[ReversiBoardPosition alloc] initWithInt:x:y]; 
		count++;
		state->state++;
	}
	state->itemsPtr = stackbuf;
	state->mutationsPtr = (unsigned long*)self;
	return count;
}

- (ReversiBoardLineRangeEnumerator*)positionEnumerator{
	ReversiBoardLineRange* line = self;
	return [[ReversiBoardLineRangeEnumerator alloc] initWithLineRange:line];
}

- (bool)isEqual:(id)object{
	if ([object isKindOfClass:[self class]]){
		return	[startPosition isEqual:[object startPosition]] && 
				[direction isEqual:[object direction]] &&
				numberOfStone == [object numberOfStone];
	}
	return false;
}

- (id)copyWithZone:(NSZone*)zone{
	return [[[self class] alloc] init:startPosition dir:direction num:numberOfStone];
}

@end
